﻿using MiniFox.Components;
using MiniFox.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiniFox.Tasks
{
    /// <summary>
    /// 任务行为
    /// </summary>
    public abstract class TaskAction : Component
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        protected TaskAction(string name)
        {
            this.Name = name;
        }
        /// <summary>
        /// 执行前触发的事件
        /// </summary>
        public event EventHandler BeforeExecution;
        /// <summary>
        /// 执行后触发的事件
        /// </summary>
        public event EventHandler AfterExecution;
        /// <summary>
        /// 
        /// </summary>
        public event EventHandler<ErrorHandleEventArgs> ErrorHandled;
        
        /// <summary>
        /// 
        /// </summary>
        public virtual void Execute()
        {
            if (this.BeforeExecution != null)
                this.BeforeExecution(this, EventArgs.Empty);
            try
            {
                Process();

            }
            catch (Exception e)
            {
                bool ignoreError = false;
                if (this.ErrorHandled != null)
                {
                    ErrorHandleEventArgs eventarg = new ErrorHandleEventArgs(e, false);
                    this.ErrorHandled(this, eventarg);
                    ignoreError = eventarg.IgnoreException;
                }
                if (!ignoreError)
                {
                    throw e;
                }

            }
            if (this.AfterExecution != null)
                this.AfterExecution(this, EventArgs.Empty);
        }
        /// <summary>
        /// 执行
        /// </summary>
        protected abstract void Process();
    }
    /// <summary>
    /// 
    /// </summary>
    public class ErrorHandleEventArgs : UnhandledExceptionEventArgs
    {
        internal ErrorHandleEventArgs(Exception exception, bool isTerminating) : base(exception, isTerminating)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        public bool IgnoreException
        {
            get;
            set;
        }
    }
}
